/*
 * @Author: your name
 * @Date: 2021-06-02 10:16:45
 * @LastEditTime: 2021-06-02 17:20:20
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \bazai_island_api\app\api\v1\token.js
 */
const Router = require('koa-router')
const router = new Router()
const { TokenValidator, NotEmptyValidator } = require('../../validators/validators')
const { User } = require('../../models/user')
const { LoginType } = require('../../lib/enum')
const { generateToken } = require('../../../core/utils')
const { Auth } = require('../../../middlewares/auth')
const { WXManager } = require('../../services/wx')
router.prefix('/v1/token')


router.post('/', async(ctx) => {
  // 校验器校验
  const v = await new TokenValidator().validate(ctx)
  // 业务逻辑
  // 1 在API接口编写
  // 2 Model 分层
  // MVC Model

  // 业务分层 Model, Service
  // Thinkphp Model Service Logic
  // Model DTO
  let token = ''
  switch (v.get('body.type')) {
    // email 
    case LoginType.USER_EMAIL:
      token = await emailLogin(v.get('body.account'), v.get('body.secret'))
      break;
    // 小程序
    case LoginType.USER_MINI_PROGRAM:
      token = await WXManager.codeToToken(v.get('body.account'))
      break;
    case LoginType.ADMIN_EMAIL:
      break;
    default:
      throw new global.errs.ParameterException('没有相应的处理函数')
  }
  ctx.body = {
    code: 200,
    token
  }
})

router.post('/verify', async(ctx) => {
  // token
  const v = await new NotEmptyValidator().validate(ctx)
  const result = Auth.verifyToken(v.get('body.token'))
  ctx.body = {
    code: 200,
    is_valid: result
  }
})

const emailLogin = async (account, password) => {
  const user = await User.verifyEmailPassword(account, password)
  return token = await generateToken(user.id, Auth.USER)
}

module.exports = router
